package Actions;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.JTable;

import Model.Author;
import Model.Manuscript;
import TableModels.AuthorTemplate;

/**
 * Removes a paper from the system
 * @author dustin striplin
 *
 */
public class UnsubmitPaper extends AbstractAction{

	
	JTable table;
	Author author;
	
	public UnsubmitPaper(JTable table, Author author) {
		this.table = table;
		this.author = author;
		this.putValue(NAME, "Unsubmit");
		this.putValue(MNEMONIC_KEY, KeyEvent.VK_U);
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		if(table.getSelectedRow() != -1) {
			//convert to models row index, since the table index changes when it is sorted
			int row = table.convertRowIndexToModel(table.getSelectedRow());
										//must cast to correct TableModel, or getManuscriptLink wont work.
			
			AuthorTemplate model = (AuthorTemplate) table.getModel();	
			
			String link = model.getManuscriptLink(row);//get link	
			Manuscript script = model.getManuscript(row);
			String confirmation = author.unsubmitPaper(script);
			
			if(confirmation.equals(Author.REMOVED)) {
				try{ 
		    		File file = new File("src/" + link);  //TODO i dont know if this will cause a problem in release
		    												//may have to create a folder outside of src
		    		
		    		if(file.delete()){
		    			model.deleteManuscript(row);
		    			table.repaint();
		    			JOptionPane.showMessageDialog(null, "Unsubmitted");
		    		}else{
		    			JOptionPane.showMessageDialog(null, "Could not unsubmit");
		    		}
		 
		    	}catch(Exception e){
		 
		    		e.printStackTrace();
		    	}
			}else{
				JOptionPane.showMessageDialog(null, "Could not unsubmit");
			}
		}
	}

}